package com.dflc.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.SaTokenException;
import com.baomidou.kaptcha.exception.KaptchaException;
import com.baomidou.kaptcha.exception.KaptchaIncorrectException;
import com.baomidou.kaptcha.exception.KaptchaNotFoundException;
import com.baomidou.kaptcha.exception.KaptchaTimeoutException;
import com.dflc.entity.rep.HttpResponseEntity;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.util.validation.ValidationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO lb <类名>
 *
 * @author libin
 * @version 1.0.0.0
 * <p>Title: GlobalExceptionHandler </p>
 * <p>Description: TODO lb </p>
 * Package: com.dflc.exception
 * Company: 数字涪陵
 * Copyright: Copyright(c) 产品研发与安全部
 * Date: 2023年03月07日 17:14
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BusinessException.class)
    public HttpResponseEntity handleRRException(BusinessException e) {
        log.error("业务异常", e);
        return HttpResponseEntity.error(500, e.getMsg());
    }


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public HttpResponseEntity handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
//        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("方法参数类型不匹配", e);
        return HttpResponseEntity.error(500,"方法参数类型不匹配");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public HttpResponseEntity handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
//        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("缺少请求参数", e);
        return HttpResponseEntity.error(500,"缺少请求参数");
    }

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public HttpResponseEntity handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
//        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("参数解析失败", e);
        return HttpResponseEntity.error(500,"参数解析失败");
    }


    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ValidationException.class)
    public HttpResponseEntity handleValidationException(ValidationException e) {
//        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("参数验证失败", e);
        return HttpResponseEntity.error(500,"参数验证失败");
    }

    /**
     * 405 - Method Not Allowed
     */
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public HttpResponseEntity handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
//        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("不支持当前请求方法", e);
        return HttpResponseEntity.error(500,"不支持当前请求方法");
    }

    /**
     * 415 - Unsupported Media Type
     */
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    public HttpResponseEntity handleHttpMediaTypeNotSupportedException(Exception e) {
//        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error("不支持当前媒体类型", e);
        return HttpResponseEntity.error(500,"不支持当前媒体类型");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public HttpResponseEntity handleDuplicateKeyException(DuplicateKeyException e) {
//        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error(e.getMessage(), e);
        return HttpResponseEntity.error(500, "数据库中已存在该记录");
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public HttpResponseEntity handleMaxSizeException(MaxUploadSizeExceededException e) {
//        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error(e.getMessage(), e);
        return HttpResponseEntity.error(500, "File too large!");
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(NotLoginException.class)
    public HttpResponseEntity handleNotLoginException(NotLoginException e) {
//        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error(e.getMessage(), e);
        return HttpResponseEntity.error(401, e.getMessage());
    }

    @ExceptionHandler(SaTokenException.class)
    public HttpResponseEntity handleMaxSizeException(SaTokenException e) {
        log.error(e.getMessage(), e);
//        log.error("uri：{}, httpMethod:{}, errMsg:{}", HttpServletRequestUtil.getRequestURI(), HttpServletRequestUtil.getRequest().getMethod(), e.getMessage());
        return HttpResponseEntity.error(403, e.getMessage());
    }

    /**
     * 验证bean类型
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public HttpResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        List<String> result = new ArrayList<>();
        e.getBindingResult().getFieldErrors().forEach((fieldError) -> {
//            result.add(Dict.create().set("field", fieldError.getField()).set("msg", fieldError.getDefaultMessage()));
            result.add(fieldError.getDefaultMessage());
        });
        return HttpResponseEntity.error(500, result.toString());
    }


    /**
     * 兜底验证ValidationException
     */
    @ExceptionHandler(javax.validation.ValidationException.class)
    public HttpResponseEntity handleValidationException(javax.validation.ValidationException e) {
        log.error(e.getMessage(), e);
        return HttpResponseEntity.error(500, e.getCause().getMessage());
    }


    @ExceptionHandler(NoHandlerFoundException.class)
    public HttpResponseEntity handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return HttpResponseEntity.error(404, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(Exception.class)
    public HttpResponseEntity handleException(Exception e) {
//        log.info(HttpServletRequestUtil.getAllRequestInfo());
        log.error(e.getMessage(), e);
        return HttpResponseEntity.error(500, "服务器异常:"+e.getCause());
    }

    @ExceptionHandler(value = KaptchaException.class)
    public HttpResponseEntity kaptchaExceptionHandler(KaptchaException kaptchaException) {
        if (kaptchaException instanceof KaptchaIncorrectException) {
            return HttpResponseEntity.error(500, "验证码不正确");
        } else if (kaptchaException instanceof KaptchaNotFoundException) {
            return HttpResponseEntity.error(500, "验证码未找到");
        } else if (kaptchaException instanceof KaptchaTimeoutException) {
            return HttpResponseEntity.error(500, "验证码过期,请重新获取验证码");
        } else {
            return HttpResponseEntity.error(500, "验证码渲染失败");
        }

    }
}
